package com.xd.core.business.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xd.common.base.CustomRowHeightColWidthHandler;
import com.xd.common.base.RowHeightColWidthModel;
import com.xd.common.constant.SysConstant;
import com.xd.common.util.AESUtil;
import com.xd.common.util.SecurityUtil;
import com.xd.core.business.dto.ContractDto;
import com.xd.core.business.entity.Contract;
import com.xd.core.business.mapper.ContractMapper;
import com.xd.core.business.service.IContractService;
import com.xd.core.business.vo.*;
import com.xd.core.mission.entity.MissionCenterInfo;
import com.xd.core.mission.mapper.MissionCenterInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ZX
 * @since 2025-02-27
 */
@Service
public class ContractServiceImpl extends ServiceImpl<ContractMapper, Contract> implements IContractService {
    @Autowired
    private ContractMapper contractMapper;
    @Value("${image.localPathDir}")
    private String localPathDir;
    @Value("${image.exportFile}")
    private String exportFile;
    @Value("${aes.key}")
    private String aesKey;
    @Autowired
    private MissionCenterInfoMapper missionCenterInfoMapper;
    @Override
    public Page<ContractVo> getContractList(ContractDto contractDto) {
        String companyType = SecurityUtil.getLoginUser().getUser().getCompanyType();
        Integer companyId = contractDto.getCompanyId();
        if (!companyType .equals(SysConstant.USER_COMPANY_TYPE_ONE) && !companyType .equals(SysConstant.USER_COMPANY_TYPE_FOUR)){//不是平台
            companyId = SecurityUtil.getLoginCompanyId();
        }
        PageHelper.startPage(contractDto.getPageNum(),contractDto.getPageSize());
        return (Page<ContractVo>)contractMapper.getContractList(contractDto,companyId);
    }


    @Override
    public Page<DeContractVo> getDetContractList(ContractDto contractDto) {
        String companyType = SecurityUtil.getLoginUser().getUser().getCompanyType();
        Integer companyId = contractDto.getCompanyId();
        if (!companyType .equals(SysConstant.USER_COMPANY_TYPE_ONE) && !companyType .equals(SysConstant.USER_COMPANY_TYPE_FOUR)){//不是平台
            companyId = SecurityUtil.getLoginCompanyId();
        }
        PageHelper.startPage(contractDto.getPageNum(),contractDto.getPageSize());
        return (Page<DeContractVo>) contractMapper.debtQueryList(contractDto,companyId);
    }

    @Override
    public void exportContractList(ContractDto contractDto, Integer id) {
        String name = "债权转让合同excel文件" + UUID.randomUUID().toString().replace("-", "");
        Integer companyId = SecurityUtil.getLoginCompanyId();
        FileOutputStream fileOutputStream = null;
        MissionCenterInfo missionCenterInfo = new MissionCenterInfo();
        missionCenterInfo.setId(id);
        missionCenterInfo.setFileName(name + ".xlsx");

        String filePath = localPathDir + exportFile + "/" + companyId;
        File dirFile = new File(filePath);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }

        try {
            List<RowHeightColWidthModel> rowHeightColWidthList = new ArrayList<>();
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 0, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 1, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 2, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 3, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 4, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 5, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 6, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 7, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 8, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 9, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 10, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 11, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 12, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 13, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 14, 20));
            File file = new File(filePath + "/" + name + ".xlsx");
            fileOutputStream = new FileOutputStream(file);

            ExcelWriter write = EasyExcel.write(fileOutputStream, IncomingInfoPageVo.class).build();
            WriteSheet writeSheet = EasyExcel.writerSheet(name).registerWriteHandler(new CustomRowHeightColWidthHandler(rowHeightColWidthList)).build();
            contractDto.setPageSize(0);
            List<DeContractVo> list = getDetContractList(contractDto);
            write.write(list, writeSheet);
            write.finish();
            fileOutputStream.flush();
            //修改文件状态 导出成功
            missionCenterInfo.setFileStatus(SysConstant.YSZT_FILE_STATUS_TOW);
            missionCenterInfo.setFileUrl(exportFile + "/" + companyId + "/" + name + ".xlsx");
            missionCenterInfoMapper.updateById(missionCenterInfo);
        } catch (Exception e) {
            //修改文件状态 导出失败
            missionCenterInfo.setFileStatus(SysConstant.YSZT_FILE_STATUS_THREE);
            missionCenterInfoMapper.updateById(missionCenterInfo);
            e.printStackTrace();
        } finally {
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void exportDeContractList(ContractDto contractDto, Integer id) {
        String name = "借款客户合同excel文件" + UUID.randomUUID().toString().replace("-", "");
        Integer companyId = SecurityUtil.getLoginCompanyId();
        FileOutputStream fileOutputStream = null;
        MissionCenterInfo missionCenterInfo = new MissionCenterInfo();
        missionCenterInfo.setId(id);
        missionCenterInfo.setFileName(name + ".xlsx");

        String filePath = localPathDir + exportFile + "/" + companyId;
        File dirFile = new File(filePath);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }

        try {
            List<RowHeightColWidthModel> rowHeightColWidthList = new ArrayList<>();
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 0, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 1, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 2, 10));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 3, 15));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 4, 10));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 5, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 6, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 7, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 8, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 9, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 10, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 11, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 12, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 13, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 14, 20));
            File file = new File(filePath + "/" + name + ".xlsx");
            fileOutputStream = new FileOutputStream(file);

            ExcelWriter write = EasyExcel.write(fileOutputStream, IncomingInfoPageVo.class).build();
            WriteSheet writeSheet = EasyExcel.writerSheet(name).registerWriteHandler(new CustomRowHeightColWidthHandler(rowHeightColWidthList)).build();
            contractDto.setPageSize(0);
            List<ContractVo> list = getContractList(contractDto);
            for (ContractVo customerInfoVo : list) {
                String decryptPhone = AESUtil.decrypt(customerInfoVo.getPhone(), aesKey);
                customerInfoVo.setPhone(decryptPhone);
            }
            write.write(list, writeSheet);
            write.finish();
            fileOutputStream.flush();
            //修改文件状态 导出成功
            missionCenterInfo.setFileStatus(SysConstant.YSZT_FILE_STATUS_TOW);
            missionCenterInfo.setFileUrl(exportFile + "/" + companyId + "/" + name + ".xlsx");
            missionCenterInfoMapper.updateById(missionCenterInfo);
        } catch (Exception e) {
            //修改文件状态 导出失败
            missionCenterInfo.setFileStatus(SysConstant.YSZT_FILE_STATUS_THREE);
            missionCenterInfoMapper.updateById(missionCenterInfo);
            e.printStackTrace();
        } finally {
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public IncomingDetailContractVo getContracts(Integer outId) {
        return contractMapper.selectContracts(outId);
    }

    @Override
    public List<ContractDetailVo> getInsuranceContracts(Integer incomingId) {
        return contractMapper.selectInsurance(incomingId);
    }
}
